package com.gotop.auth.granter;

import com.gotop.common.enums.EnumTokenGranter;
import com.gotop.common.enums.EnumUser;
import com.gotop.auth.service.IUserService;
import com.gotop.auth.utils.TokenUtil;
import com.gotop.common.config.redis.RedisUtil;
import com.gotop.common.exception.SecureException;
import com.gotop.common.redis.CacheNames;
import com.gotop.common.utils.DigestUtil;
import com.gotop.common.utils.WebUtil;
import com.gotop.common.utils.auth.TokenParameter;
import com.gotop.info.UserInfo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @program: cem
 * @description:
 * @author: superfish
 * @create: 2020-12-17 16:02
 **/
@Component
@AllArgsConstructor
public class CaptchaTokenGranter implements ITokenGranter {

    public static final String GRANT_TYPE = EnumTokenGranter.CAPTCHA_TOKEN_GRANTER.getMsg();

    @Autowired
    private IUserService userService;
    private RedisUtil redisUtil;

    @Override
    public UserInfo grant(TokenParameter tokenParameter) {
        final HttpServletRequest request = WebUtil.getRequest();

        final String key = request.getHeader(TokenUtil.CAPTCHA_HEADER_KEY);
        final String code = request.getHeader(TokenUtil.CAPTCHA_HEADER_CODE);
        redisUtil.set(CacheNames.CAPTCHA_KEY + key, code, 1L, TimeUnit.MINUTES);
        // 获取验证码
        final String redisCode = String.valueOf(redisUtil.get(CacheNames.CAPTCHA_KEY + key));
        // 判断验证码
        if (code == null || !StringUtils.equalsIgnoreCase(redisCode, code)) {
            throw new SecureException(TokenUtil.CAPTCHA_NOT_CORRECT);
        }

        final String tenantId = tokenParameter.getArgs().getStr("tenantId");
        final String account = tokenParameter.getArgs().getStr("account");
        final String password = tokenParameter.getArgs().getStr("password");
        UserInfo userInfo = null;
        if (StringUtils.isNoneBlank(account, password)) {
            // 获取用户类型
            final String userType = tokenParameter.getArgs().getStr("userType");
            // 根据不同用户类型调用对应的接口返回数据，用户可自行拓展
            if (userType.equals(EnumUser.WEB.getName())) {
                userInfo = userService.userInfo(tenantId, account, DigestUtil.encrypt(password));
            } else if (userType.equals(EnumUser.APP.getName())) {
                userInfo = userService.userInfo(tenantId, account, DigestUtil.encrypt(password));
            } else {
                userInfo = userService.userInfo(tenantId, account, DigestUtil.encrypt(password));
            }
        }
        return userInfo;
    }

}